import React, { FC, MutableRefObject, useEffect } from 'react';
import FieldItem, { FieldItemProps } from './FieldItem';
import { IFormLayoutProps } from '@formily/antd/esm/form-layout';
import { Form } from 'antd';
import { SubWindowType } from '../../interfaces';
import './index.less';

interface FieldFormProps {
  formItemsRef: MutableRefObject<any>;
  layout?: IFormLayoutProps['layout'];
  fields?: FieldItemProps[];
  initialValues: SubWindowType;
  otherFormItem?: React.ReactNode;
}

const FieldForm: FC<FieldFormProps> = (props) => {
  const { fields, initialValues, formItemsRef, otherFormItem } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    // 兼容老版本的高度配置
    if (initialValues && initialValues?.height) {
      if (!initialValues?.maxHeight) {
        initialValues['maxHeight'] = {
          height: 60,
          suffix: '%',
        };
      }
      if (!initialValues?.minHeight) {
        initialValues['minHeight'] = {
          height: 45,
          suffix: '%',
        };
      }
    }
    // 兼容老版本的操作按钮显示配置
    if (initialValues?.actionDisplaySetup) {
      if (!initialValues.tableHeaderBtnShow) {
        initialValues['tableHeaderBtnShow'] = initialValues.actionDisplaySetup
      }
      if (!initialValues.inLineBtnShow) {
        initialValues['inLineBtnShow'] = initialValues.actionDisplaySetup
      }
    }
    form.setFieldsValue({
      ...initialValues,
      auth: form.getFieldValue('auth'),
    });
  }, []);
  return (
    <Form
      form={form}
      initialValues={initialValues}
      colon={false}
      labelCol={{ span: 8 }}
      labelAlign="left"
      onValuesChange={(_, allValues) => {
        formItemsRef.current.formItems = allValues;
      }}
      style={{ height: 'auto' }}
      className='table-form'
    >
      {fields?.map((field) => (
        <FieldItem key={field.name} {...field} values={initialValues} />
      ))}
      {otherFormItem}
    </Form>
  );
};

export default FieldForm;
